package com.laike.pay.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.laike.pay.R;
import com.laike.pay.base.BaseActivity;
import com.laike.pay.bean.PayOrder;
import com.laike.pay.http.BaseCallback;
import com.laike.pay.http.HttpRetrofit;
import com.laike.pay.http.ParamsUtils;
import com.laike.pay.http.Result;
import com.laike.pay.http.api.ApiName;
import com.laike.pay.http.api.SerivceApi;
import com.laike.pay.utils.Dialogutils;
import com.laike.pay.utils.SharedPreferencesUtils;
import com.laike.pay.utils.ToastUtils;

import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Response;

public class BrushCardManagerActivity extends BaseActivity implements Dialogutils.OnDismissListener, BaseCallback<Result<PayOrder>> {
    @Bind(R.id.detail_layout)
    LinearLayout detailLayout;
    @Bind(R.id.reimburse_layout)
    LinearLayout reimburseLayout;
    @Bind(R.id.pre_authorization_layout)
    LinearLayout preAuthorizationLayout;
    @Bind(R.id.system_manager_layout)
    LinearLayout systemManagerLayout;
    @Bind(R.id.settlement_layout)
    LinearLayout settlementLayout;
    @Bind(R.id.cashier_top)
    LinearLayout cashierTop;
    private String certificateNumber;//凭证号；
    @Override
    public int getContentViewResId() {
        return R.layout.activity_brush_card_managr;
    }

    @Override
    public void intiViews() {
        detailLayout.setOnClickListener(this);
        reimburseLayout.setOnClickListener(this);
        preAuthorizationLayout.setOnClickListener(this);
        systemManagerLayout.setOnClickListener(this);
        settlementLayout.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id = view.getId();
        switch (id) {
            case R.id.detail_layout:
                Intent intent1 = new Intent(BrushCardManagerActivity.this, TransactionActivity.class);
                intent1.putExtra("pay_type", 1);
                startActivity(intent1);
                break;
            case R.id.reimburse_layout:
                Dialogutils.showDialog(this, "", this);
                break;
            case R.id.pre_authorization_layout:
                onAuth();
                break;
            case R.id.system_manager_layout:
                onSetting();
                break;
            case R.id.settlement_layout:
                onSettle();
                break;
        }
    }

    /**
     * 结算
     */
    private void onSettle() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    JSONObject json = new JSONObject();
                    json.put("transType", "SETTLE");
                    json.put("appId", SharedPreferencesUtils.getAppid());
                    payHelper.doTrans(json.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 系统设置
     */
    private void onSetting() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    JSONObject json = new JSONObject();
                    json.put("transType", "SETTING");
                    json.put("appId", SharedPreferencesUtils.getAppid());
                    payHelper.doTrans(json.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 预授权
     */
    private void onAuth() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    JSONObject json = new JSONObject();
                    json.put("transType", "AUTH");
                    json.put("transAmount", "1");
                    json.put("appId", SharedPreferencesUtils.getAppid());
                    String result = payHelper.doTrans(json.toString());
                    json = new JSONObject(result);
                    final String rspCode = json.getString("rspCode");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if ("0".equals(rspCode)) {
                                Toast.makeText(BrushCardManagerActivity.this, "预授权成功", Toast.LENGTH_SHORT).show();
                            } else
                                Toast.makeText(BrushCardManagerActivity.this, "预授权失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 交易撤销
     */
    private void onCancleTrans() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    JSONObject json = new JSONObject();
                    json.put("transType", "VOID");
                    json.put("voucherNo", certificateNumber);
                    json.put("appId", SharedPreferencesUtils.getAppid());
                    String result = payHelper.doTrans(json.toString());
                    json = new JSONObject(result);
                    final String rspCode = json.getString("rspCode");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if ("0".equals(rspCode)) {
                                ToastUtils.showToast(BrushCardManagerActivity.this, "交易撤销成功", 3000);
                                HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class).refund(SharedPreferencesUtils.getAppid(), ApiName.RE_FUND, ParamsUtils.BrushRefund(certificateNumber), certificateNumber
                                        , "", SharedPreferencesUtils.getWorkMenId()).enqueue(BrushCardManagerActivity.this);
                            } else
                                Toast.makeText(BrushCardManagerActivity.this, "交易撤销失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public String setTitle() {
        return getString(R.string.brush_card_manager);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    public void onAttachedToWindow() {
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
        super.onAttachedToWindow();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            Intent intent = new Intent(this, CollectMoneyActivity.class);
            startActivity(intent);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onConfirm(String ContentTxet) {
        if (TextUtils.isEmpty(ContentTxet)) {
            return;
        }
        certificateNumber = ContentTxet;
        onCancleTrans();
    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onResponse(Call<Result<PayOrder>> call, Response<Result<PayOrder>> response) {
        if (response.code() == 200) {
            if (response.body().getStatus().equals("1")) {
                ToastUtils.showToast(this, "订单状态已修改", 5000);
            } else {
                ToastUtils.showToast(this, response.body().getInfo(), 5000);
            }
        }
    }

    @Override
    public void onFailure(Call<Result<PayOrder>> call, Throwable t) {
        Log.e("onFailure", "error message:" + t.getMessage());
    }

}
